﻿using Microsoft.Extensions.Options;
using MongoDB.Driver;

namespace ChatGPT.Repository;

/// <summary>
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class MongoRepository<TEntity> : IMongoRepository<TEntity>
{
    private readonly IMongoDatabase _database;


    public MongoRepository(IOptions<MongoConfig> config)
    {
        var url = new MongoUrl(config.Value.Connection);
        var clientSettings = MongoClientSettings.FromUrl(url);
        _database = new MongoClient(clientSettings).GetDatabase(url.DatabaseName);
    }

    /// <summary>
    ///     Adds the specified entity.
    /// </summary>
    /// <param name="entity">The entity.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns></returns>
    public virtual async Task AddAsync(TEntity entity)
    {
        var collectionName = typeof(TEntity).Name;
        var collection = _database.GetCollection<TEntity>(collectionName);
        await collection.InsertOneAsync(entity);
    }

    /// <summary>
    /// </summary>
    /// <param name="filter"></param>
    /// <param name="sort"></param>
    /// <returns></returns>
    public List<TEntity> Find(FilterDefinition<TEntity> filter, SortDefinition<TEntity> sort)
    {
        var collectionName = typeof(TEntity).Name;
        var collection = _database.GetCollection<TEntity>(collectionName);
        return collection.Find(filter).Sort(sort).ToList();
    }
}